import type { GetUserInfoResponseData , LoginParamsData } from "@/api/userInfo";
import type {RouteRecordRaw} from 'vue-router'
import { defineStore } from "pinia";
import {allAsyncRoutes,staticRoutes,anyRoute} from '@/router/routes'
import {default as userInfoApi} from '@/api/userInfo'
import router from "@/router";
import cloneDeep from 'lodash/cloneDeep'



interface UserInfoStoreStateData{
  token:string,
  userInfo:GetUserInfoResponseData,
  menuRoutes:Array<RouteRecordRaw>
}

// 定义一个方法充值userInfo数据
function initUserInfo(target:GetUserInfoResponseData,source:GetUserInfoResponseData){
  Object.assign(target,source)
}

// 定义一个方法用来过滤异不路由
function filterAsyncRoutes(allAsyncRoutes:RouteRecordRaw[],routeNames:string[]){
  let asynsRoutes = allAsyncRoutes.filter(item=>{
    if(routeNames.includes(item.name as string)){
      if(item.children&&item.children.length){
        item.children=filterAsyncRoutes(item.children,routeNames)
      }
      return true
    }
  })
  return asynsRoutes
}

// 定义一个方法一次添加多个路由
function addRoutes(asyncAndAnyRoute:RouteRecordRaw[]){
  asyncAndAnyRoute.forEach(item=>{
    router.addRoute(item)
  })
}

// 定义一个方法清除每次退出时要清空的路由和添加的静态路由
function resetRoutes(){
  const routers =router.getRoutes()
  routers.forEach(item=>{
    router.removeRoute(item.name as string)
  })
  // 添加静态路由
  addRoutes(staticRoutes)
}

export const useUserInfoStore=defineStore('userInfo',{
  state:():UserInfoStoreStateData=>{
    return {
      token:localStorage.getItem('token')||'',
      userInfo:{
        routes:[],
        buttons:[],
        roles:[],
        name:'',
        avatar:''
      },
      // 给menuRoutes先加入静态了路由
      menuRoutes:staticRoutes
    }
  },
  actions:{
    async login(loginParams:LoginParamsData){
      try{
        const result = await userInfoApi.login(loginParams)
        this.token = result.token
        localStorage.setItem('token',result.token)
        return 'ok'
      }catch(error){
        return Promise.reject('登录失败')
      }
    },
    async getUserInfo(){
      try {
        const result = await userInfoApi.getUserInfo()
        this.userInfo = result
        // 获取用户的异步路由
        let routeNames=result.routes
        // 从所有的异步路由过滤出用户的异步路由
        let userAsyncRoutes = filterAsyncRoutes(cloneDeep(allAsyncRoutes),routeNames)
        addRoutes(userAsyncRoutes.concat(anyRoute))
        this.menuRoutes=staticRoutes.concat(userAsyncRoutes,anyRoute)
        return 'ok'
      }catch(error){
        return Promise.reject('登录失败')
      }
    },
    reset(){
      this.token=''
      localStorage.removeItem('token')
      initUserInfo(this.userInfo,{
          routes:[],
          buttons:[],
          roles:[],
          name:'',
          avatar:''
          },
        )
    },
    async logout(){
      try{
        await userInfoApi.logout()
        resetRoutes()
        this.reset()
        return 'ok'
      }catch(error){
        return Promise.reject('退出失败')
      }
    }
  }
})